package com.lhcai.lc.category.designsimulate;

/**
 * 2502. 设计内存分配器
 *
 * @author liuhuaicai
 * @since 2024-10-30 21:27
 */
public class Allocator {
    public static void main(String[] args) {
        Allocator allocator = new Allocator(7);
        System.out.println(allocator.allocate(3, 1));
        System.out.println(allocator.allocate(5, 2));
        System.out.println(allocator.free(1));
        System.out.println(allocator.free(3));
        allocator.allocate(1, 1);
        allocator.allocate(1, 1);
        allocator.free(1);
        allocator.allocate(10, 2);
        allocator.free(7);
    }

    int[] dis;
    int length;

    public Allocator(int n) {
        length = n;
        dis = new int[n];
    }

    public int allocate(int size, int mID) {
        // 超大，直接返回
        if (size > length) {
            return -1;
        }
        int i = 0;
        while (i < length) {
            // 直到空单元
            while (i < length && dis[i] != 0) {
                i++;
            }
            // 初始为此处
            int start = i;
            while (i < length && dis[i] == 0) {
                i++;
                // 符合条件时，将单元赋值为mID
                if (i - start >= size) {
                    for (int j = start; j < start + size; j++) {
                        dis[j] = mID;
                    }
                    return start;
                }
            }
            i++;
        }
        return -1;
    }

    public int free(int mID) {
        int i = 0;
        int count = 0;
        while (i < length) {
            if (dis[i] == mID) {
                count++;
                dis[i] = 0;
            }
            i++;
        }
        return count;
    }
}
